package com.raincat.tools.multimediapickertools.utils;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.raincat.tools.R;

import java.util.List;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2019/02/22
 *     desc   : 下拉列表
 *     version: 1.0
 * </pre>
 */

public class DropDownPopupWindow extends PopupWindow {
    private Context context;
    private int index = -1;
    private ImageView iv_bk;
    private ListView listView;
    private OnListItemClickListener listener;

    public DropDownPopupWindow(Context context) {
        super(context);
        this.context = context;
    }

    /**
     * @param bucketIndex 当前选中的文件夹编号
     * @param itemList    文件夹列表
     */
    public DropDownPopupWindow(Context context, View parent, int bucketIndex, List<MultiMediaBucket> itemList, OnListItemClickListener listener) {
        super(context);
        this.context = context;
        this.listener = listener;

        View view = View.inflate(this.context, R.layout.picker_view_dropdown, null);
        setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        setBackgroundDrawable(new ColorDrawable());
        setFocusable(true);
        setOutsideTouchable(true);
        setContentView(view);
        showAsDropDown(parent);
        update();

        iv_bk = view.findViewById(R.id.iv_bk);
        listView = view.findViewById(R.id.listView);
        iv_bk.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_ins));
        iv_bk.setVisibility(View.VISIBLE);
        listView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.push_top_in));
        listView.setVisibility(View.VISIBLE);

        //限制弹出框的高度
        if (itemList.size() > 5) {
            setListVisibleCount(context, 5);
        }

        ListAdapter adapter = new ListAdapter(context, itemList, bucketIndex);
        listView.setAdapter(adapter);
        listView.setSelection(bucketIndex);
        iv_bk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                dismiss();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                index = i;
                dismiss();
            }
        });
    }

    private void dismiss2() {
        super.dismiss();
    }

    public void dismiss() {
        iv_bk.startAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_outs));
        listView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.push_top_out));
        if (listener != null) {
            listener.onClick(index);
        }
        new Handler().postDelayed(new Runnable() {
            public void run() {
                dismiss2();
            }
        }, 300);
    }

    private void setListVisibleCount(Context context, int count) {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                (int) (71.0F * context.getResources().getDisplayMetrics().density + 0.5F) * count);
        listView.setLayoutParams(lp);
    }

    private static class ListAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater mInflater;

        private int checkedTextColor;
        private int unCheckTextColor;
        private int clickIndex;
        private List<MultiMediaBucket> multiMediaBucketList;

        ListAdapter(Context context, List<MultiMediaBucket> multiMediaBucketList, int clickIndex) {
            this.context = context;
            mInflater = LayoutInflater.from(context);
            this.multiMediaBucketList = multiMediaBucketList;
            this.clickIndex = clickIndex;

            TypedValue typedValue = new TypedValue();
            context.getTheme().resolveAttribute(R.attr.picker_dropDownPopupWindow_normalTextColor, typedValue, true);
            unCheckTextColor = context.getResources().getColor(typedValue.resourceId);
            context.getTheme().resolveAttribute(R.attr.picker_dropDownPopupWindow_highLightTextColor, typedValue, true);
            checkedTextColor = context.getResources().getColor(typedValue.resourceId);
        }

        public int getCount() {
            return multiMediaBucketList.size();
        }

        public Object getItem(int paramInt) {
            return multiMediaBucketList.get(paramInt);
        }

        public long getItemId(int paramInt) {
            return paramInt;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = mInflater.inflate(R.layout.picker_view_dropdownitem, parent, false);
                holder.text = convertView.findViewById(R.id.tv_content);
                holder.img = convertView.findViewById(R.id.iv_icon);

                convertView.setTag(holder);
            } else
                holder = (Holder) convertView.getTag();

            String content = multiMediaBucketList.get(position).bucketName + "(" + multiMediaBucketList.get(position).multiMediaItemList.size() + ")";
            holder.text.setText(content);

            if (multiMediaBucketList.get(position).multiMediaItemList.size() <= 0)
                holder.img.setImageBitmap(null);
            else
                Glide.with(context).asBitmap().load(multiMediaBucketList.get(position).multiMediaItemList.get(0).path).into(holder.img);

            if (clickIndex != position)
                holder.text.setTextColor(unCheckTextColor);
            else
                holder.text.setTextColor(checkedTextColor);

            ((ViewGroup) convertView).setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            return convertView;
        }

        static class Holder {
            ImageView img;
            TextView text;
        }
    }

    public interface OnListItemClickListener {
        void onClick(int index);
    }

    /**
     * 防止安卓8以上弹出框位置错误
     */
    @Override
    public void showAsDropDown(View anchor) {
        if (Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
    }
}
